<script setup lang="ts">
import {
  cardAddCardApi,
  cardGetCardDetailApi,
  cardRechargeApi,
  cardUpdateCardApi,
} from '@/apis/card'
import type { CardDetail } from '@/types/card'
import { ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'

const { query } = useRoute()
const router = useRouter()
// 标题
let title = ref('添加月卡')
// 车辆信息表单
const carFormRef = ref()
const defaultCarForm = {
  personName: '', // 车主姓名
  phoneNumber: '', // 联系方式
  carNumber: '', // 车牌号
  carBrand: '', // 车辆品牌
}
const carForm = ref({
  personName: '', // 车主姓名
  phoneNumber: '', // 联系方式
  carNumber: '', // 车牌号
  carBrand: '', // 车辆品牌
})
const carRules = {
  personName: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }],
  phoneNumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  carNumber: [
    { required: true, message: '请输入车牌号码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        const plateNumberRegex =
          /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使]{1}[A-Z]{1}[A-Z0-9]{5,6}$/
        if (plateNumberRegex.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的车牌号'))
        }
      },
      trigger: 'blur',
    },
  ],
  carBrand: [{ required: true, message: '请输入车辆品牌', trigger: 'blur' }],
}
// 缴费信息表单
const freeFormRef = ref()
const defaultFreeForm = {
  payTime: [], // 支付时间
  paymentAmount: '', // 支付金额
  paymentMethod: '', // 支付方式
}
let freeFrom = ref({
  payTime: [''], // 支付时间
  paymentAmount: '', // 支付金额
  paymentMethod: '', // 支付方式
})
const freeRules = {
  payTime: [{ required: true, message: '请选择日期', trigger: 'blur' }],
  paymentAmount: [
    { required: true, message: '请输入支付金额', trigger: 'blur' },
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'blur' },
  ],
}
// 编辑 | 续费
let cardDetail = ref<CardDetail>()
const getCardDetail = async (id?: any, flag?: any) => {
  if (id && flag) {
    title.value = '月卡续费'
    const res = await cardGetCardDetailApi(id)
    console.log('月卡续费', res)
    const {
      personName,
      phoneNumber,
      carNumber,
      carBrand,
      carInfoId,
      cardEndDate,
    } = res
    carForm.value = { personName, phoneNumber, carNumber, carBrand }
    cardDetail.value = {
      carInfoId: carInfoId,
      cardEndDate: cardEndDate,
    } as CardDetail
  } else if (id) {
    title.value = '编辑月卡'
    cardDetail.value = await cardGetCardDetailApi(id)
    const {
      personName,
      phoneNumber,
      carNumber,
      carBrand,
      cardStartDate,
      cardEndDate,
      paymentAmount,
      paymentMethod,
    } = cardDetail.value

    carForm.value = { personName, phoneNumber, carNumber, carBrand }
    freeFrom.value = {
      paymentAmount,
      paymentMethod,
      payTime: [cardStartDate, cardEndDate],
    }
  } else {
    title.value = '添加月卡'
  }
}
getCardDetail(query.id, query.flag)
// 日期选择器
const disabledDate = (time: Date) => {
  if (cardDetail.value?.carInfoId && !cardDetail.value?.rechargeId) {
    // 月卡续费
    if (
      new Date().getTime() <
      new Date(cardDetail.value?.cardEndDate).getTime() + 24 * 60 * 60 * 1000
    ) {
      return (
        time.getTime() <
        new Date(cardDetail.value.cardEndDate).getTime() + 24 * 60 * 60 * 1000
      )
    } else {
      return time.getTime() + 24 * 60 * 60 * 1000 < new Date().getTime()
    }
  } else if (cardDetail.value?.rechargeId) {
    // 编辑月卡
    return false
  } else {
    // 添加月卡
    return time.getTime() + 24 * 60 * 60 * 1000 < new Date().getTime()
  }
}
// 重置表单
const onReset = () => {
  carForm.value = { ...defaultCarForm }
  freeFrom.value = { ...defaultFreeForm }
  carFormRef.value.resetFields()
  freeFormRef.value.resetFields()
}
// 提交表单
const onSubmit = async () => {
  await carFormRef.value.validate()
  await freeFormRef.value.validate()
  // 公共参数
  const params = {
    cardStartDate: freeFrom.value.payTime[0],
    cardEndDate: freeFrom.value.payTime[1],
    paymentAmount: freeFrom.value.paymentAmount,
    paymentMethod: freeFrom.value.paymentMethod,
  }

  if (cardDetail.value?.carInfoId && !cardDetail.value?.rechargeId) {
    // 月卡续费
    const finalParams = {
      ...params,
      carInfoId: cardDetail.value.carInfoId,
    }
    await cardRechargeApi(finalParams)
    ElMessage.success('续费成功~')
  } else if (cardDetail.value?.rechargeId) {
    // 编辑月卡
    const finalParams = {
      ...params,
      ...carForm.value,
      carInfoId: cardDetail.value.carInfoId,
      rechargeId: cardDetail.value.rechargeId,
    }
    console.log(finalParams)
    await cardUpdateCardApi(finalParams)
    ElMessage.success('编辑成功~')
  } else {
    // 添加月卡
    const finalParams = {
      ...params,
      ...carForm.value,
    }
    await cardAddCardApi(finalParams)
    ElMessage.success('添加成功~')
  }

  onReset()
  router.back()
}
</script>

<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :icon="ArrowLeft" @back="$router.back()">
        <template #content>
          <span class="text-large font-600 mr-3"> {{ title }} </span>
        </template>
        <template #extra>
          <span>黑马管理员</span>
        </template>
      </el-page-header>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <el-form
          label-width="100px"
          :model="carForm"
          :rules="carRules"
          ref="carFormRef"
        >
          <el-form-item label="车主姓名:" prop="personName">
            <el-input
              placeholder="请输入车主姓名"
              v-model="carForm.personName"
              :disabled="cardDetail?.carInfoId && !cardDetail?.rechargeId"
            />
          </el-form-item>
          <el-form-item label="联系方式" prop="phoneNumber">
            <el-input
              placeholder="请输入联系方式"
              v-model="carForm.phoneNumber"
              :disabled="cardDetail?.carInfoId && !cardDetail?.rechargeId"
            />
          </el-form-item>
          <el-form-item label="车牌号码" prop="carNumber">
            <el-input
              placeholder="请输入车牌号码"
              v-model="carForm.carNumber"
              :disabled="cardDetail?.carInfoId"
            />
          </el-form-item>
          <el-form-item label="车辆品牌" prop="carBrand">
            <el-input
              placeholder="请输入车辆品牌"
              v-model="carForm.carBrand"
              :disabled="cardDetail?.carInfoId && !cardDetail?.rechargeId"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="form-container">
        <div class="title">
          {{
            cardDetail?.carInfoId && !cardDetail?.rechargeId
              ? '月卡缴费信息'
              : '最近一次缴费信息'
          }}
        </div>
        <el-form
          label-width="100px"
          :model="freeFrom"
          :rules="freeRules"
          ref="freeFormRef"
        >
          <el-form-item label="有效日期:" prop="payTime">
            <el-date-picker
              type="daterange"
              v-model="freeFrom.payTime"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              range-separator="至"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="支付金额:" prop="paymentAmount">
            <el-input
              placeholder="请输入支付金额"
              v-model="freeFrom.paymentAmount"
            />
          </el-form-item>
          <el-form-item label="支付方式:" prop="paymentMethod">
            <el-select
              placeholder="请选择支付方式"
              v-model="freeFrom.paymentMethod"
            >
              <el-option label="支付宝" value="Alipay" />
              <el-option label="微信" value="WeChat" />
              <el-option label="现金支付" value="Cash" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    background-color: #fff;
    padding: 20px 20px;
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
        border-bottom: 1px solid rgb(237, 237, 237, 0.9);
      }

      .el-form {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 20px;
        padding: 30px 65px 24px;

        .el-form-item {
          width: 50%;
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
